<template>
  <!-- flex-row 使得子元素水平排列 -->
  <div class="header-controls absolute top-10 right-0 flex flex-row" @keydown.k="handleOpenModal" tabindex="0">
    <span class="ob-drop-shadow" data-dia="search" @click="handleOpenModal">
      <svg-icon icon-class="search" />
    </span>
    <!--  Element Plus 的 Dropdown 组件，支持 @command 事件来处理菜单项的选择：
      监听用户选择的命令（例如语言切换），并将相应的命令值传递给 handleCommand 方法。-->
    <Dropdown v-if="multiLanguage === 1" @command="handleClick">
      <span class="ob-drop-shadow" data-dia="language">
        <svg-icon icon-class="globe"></svg-icon>
        <span v-if="$i18n.locale === 'zh'">中文</span>
        <span v-if="$i18n.locale === 'en'">English</span>
      </span>

      <DropdownMenu>
        <DropdownItem name="zh">中文</DropdownItem>
        <DropdownItem name="en">English</DropdownItem>
      </DropdownMenu>
    </Dropdown>
    <template v-if="userInfo === ''">
      <span @click="openLoginModal">登录</span>
    </template>
    <template v-else>
      <Dropdown hover>
        <span>
          <div>
            <div>
              <img :src="userInfo.avatar" alt="" class="">
            </div>
          </div>
        </span>
        <DropdownMenu>
          <template v-if="!isMobile">
            <DropdownItem @click="OpenPersonalCenter">个人中心</DropdownItem>
          </template>
          <DropdownItem @click="logout">退出登录</DropdownItem>
        </DropdownMenu>
      </Dropdown>
    </template>
    <span no-hover-effect class="ob-drop-shadow" data-dia="light-switch">
      <ThemeToggle />
    </span>
  </div>
</template>

<script lang="ts">
import { defineComponent, reactive, toRef, getCurrentInstance } from 'vue'
import { Dropdown, DropdownItem, DropdownMenu } from '@/components/Dropdown';
import ThemeToggle from '@/components/ToggleSwitch/ThemeToggle.vue'
import { useI18n } from 'vue-i18n';
import { useRoute, useRouter } from 'vue-router'
import { useUserStore } from '@/store/user'
import { useCommonStore } from '@/store/common'
import { useAppStore } from '@/store/app'
import { useSearchStore } from '@/store/search'
import api from '@/api/api'
import SvgIcon from '@/components/SvgIcon/index.vue'

export default defineComponent({
  name: 'Controls',
  components: {
    SvgIcon,
    Dropdown,
    DropdownItem,
    DropdownMenu,
    ThemeToggle
  },
  setup() {
    const { t } = useI18n();
    // 在 Vue 3 中，获取到当前组件的实例，appContext.config.globalProperties 对应 Vue 2 中挂载在 Vue.prototype 上的属性或方法。
    const proxy: any = getCurrentInstance()?.appContext.config.globalProperties;
    const route = useRoute();
    const router = useRouter();
    const userStore = useUserStore();
    const commonStore = useCommonStore();
    const appStore = useAppStore();
    const searchStore = useSearchStore();
    const loginInfo = reactive({
      username: '' as any,
      password: '' as any,
      code: '' as any,
    })
    const reactiveDate = reactive({
      loginDialogVisible: false as any,
      registerDialogVisible: false as any,
      forgetPasswordDialogVisible: false as any,
      articlePasswordDialogVisible: false as any,
      articlePassword: '' as any,
      articleId: '' as any
    })

    const handleClick = (name: string) => {
      appStore.setLocale(name);
    }
    const handleOpenModal: any= (status: boolean) => {
      searchStore.setOpenModal(status);
    }
    const OpenPersonalCenter = () => {
      userStore.userVisible = true;
    }
    const openLoginModal = () => {
      reactiveDate.loginDialogVisible = true;
    }
    const openRegisterModal = () => {
      loginInfo.code = '';
      reactiveDate.loginDialogVisible = false;
      reactiveDate.registerDialogVisible = true;
    }

    const returnLoginDialog = () => {
      reactiveDate.registerDialogVisible = false;
      reactiveDate.forgetPasswordDialogVisible = false;
      reactiveDate.loginDialogVisible = true;
    }

    const openForgetPasswordModal = () => {
      loginInfo.code = '';
      reactiveDate.loginDialogVisible = false;
      reactiveDate.forgetPasswordDialogVisible = true;
    }

    const login = () => {
      if(loginInfo.username.trim() === '' || loginInfo.password.trim() === '') {
        proxy.$notify.warning('用户名或密码不能为空');
        return
      }
      let params = new URLSearchParams();
      params.append('username', loginInfo.username);
      params.append('password', loginInfo.password);
      api.login(params).then((res: any) => {
        if(res.code === 200) {
          userStore.userInfo(res.data);
          sessionStorage.setItem('token', res.data.token);
          userStore.token(res.data.token);
          proxy.$notify.success('登录成功');
          reactiveDate.loginDialogVisible = false;
        } else {
          proxy.$notify.error(res.msg);
        }
      }).catch((err: any) => {
        proxy.$notify.error(err.msg);
      })
    }
    const logout = () => {
      api.logout().then((res: any) => {
        if (res.code === 200) {
          userStore.userInfo = '';
          sessionStorage.removeItem('token');
          userStore.token = '';
          userStore.accessArticle = [];
          proxy.$notify.success('退出登录成功');
          router.push({ name: 'Home' });
        }
      })
    }

    return {
      handleClick,
      handleOpenModal,
      OpenPersonalCenter,
      openLoginModal,
      login,
      logout,
      userInfo: toRef(userStore.$state, 'userInfo'),
      isMobile: toRef(commonStore.$state, 'isMobile')
    };
  },
});
</script>

<style lang="scss" scoped>
.header-controls {
  span {
    display: flex;
    justify-content: center; /* 水平居中 */
    align-items: center;  /* 垂直居中 */
    color: #fff;
    .svg-icon {
      stroke: #fff;  /* 字体颜色 */
      height: 2rem;
      width: 2rem;
      margin-right: 0.5rem;
      pointer-events: none;
    }
  }
}

</style>